package com.xiaozhen.auth.service;

import com.xiaozhen.common.core.domain.R;
import com.xiaozhen.auth.feign.SysUserService;
import com.xiaozhen.auth.model.OauthUser;
import com.xiaozhen.common.core.domain.system.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/8/5 16:52
 * @description:
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        R<SysUser> result = sysUserService.selectByUsername(username);
        SysUser userinfo = result.getData();
        System.out.println("userinfo:" + userinfo);
        //需要构造org.springframework.security.core.userdetails.User 对象包含账号密码还有用户的角色
        if (userinfo != null) {
            User user = new User(userinfo.getUserName(), userinfo.getPassword(),
                    AuthorityUtils.createAuthorityList("admin"));
            return new OauthUser(userinfo, user);
        } else {
            throw new UsernameNotFoundException("用户[" + username + "]不存在");
        }
    }
}
